//房源panal
var gridStoreJingJ=null;
Ext.define('customer.subscribe.add.estatePanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
		var me=this;
		var row_1={
				id:"isPaydepositTrue",
				fieldDefaults: {
			            labelAlign: 'top',
			            msgTarget: 'side'
			    },
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
			    border: false,
				layout: 'hbox',
				items: [{
		            items: [{
		            	xtype:'container',
		            	layout:'hbox',
		            	border:true,
		            	items:[
							{
							    xtype:'textfield',
							    name: 'subscribeId',
							    id: 'subscribeId',
							    hidden: true,
							    readOnly:true
							},
		            		{xtype: "textfield", id: "projectId", name: "projectId", hidden: true},
		            		{
		            		xtype:'textfield',
			                fieldLabel: '房号',
			                name: 'combinedName',
			                readOnly:true
			                },{
			                	xtype:'button',
			                	text:'选择房源',
			                	margin: 5,
			                	iconCls:'icon-search', 
			                	id:'changeHouse',
			           		    handler: function() {
			           		 	    var selectWindow=Ext.create('component.estate.selectWindow',{
			           		 	        callbackFun: function (record) {
			           		 	    	var result=Ext.JSON.decode(record);
				           		 		var form=me.getForm();
			           		 	    	form.setValues(result);
			           		 	       
					  	        	  	var subscribeInfoForm=Ext.getCmp("subscribeInfoForm").getForm();
					  	        	  	if(result.floorType=="1"){
						  	        	  	 result.discountAfterAmount=0;
						  	        	  	 //result.discountRateDisplay="注：折扣大于等于"+(100-result.discountRate)+"%将发起购房折扣审批，且审批完成后才生效";
						  	        	  	 //隐藏折后总价、显示折扣比例
						  	        	  	 Ext.getCmp('discountAfterPrice').setVisible(false);
						  	        	  	 Ext.getCmp("discountRate").setVisible(true);
						  	        	  	subscribeInfoForm.findField("discountAfterAmount").setReadOnly(false);
					  	        	  	}else if(result.floorType=="0"){
					  	        	  		result.discountAfterAmount=0;
					  	        	 	    //result.discountRateDisplay="注：按折后总价低于"+result.discountRate+"元将发起购房折扣审批，且审批完成后才生效";
					  	        	 	    //显示折后总价、隐藏折扣比例
					  	        	 	    Ext.getCmp('discountAfterPrice').setVisible(true);
					  	        	 	    Ext.getCmp("discountRate").setVisible(false);
					  	        	 	    subscribeInfoForm.findField("discountAfterAmount").setReadOnly(true);
					  	        	  	}
					  	        	    result.discountRateHidden=result.discountRate;
				 			 	        subscribeInfoForm.findField("isCalculate").setValue("1"); 
				 			 	        subscribeInfoForm.findField("remark").setValue(""); 
				 	        	    	subscribeInfoForm.setValues(result); 
			           		 		},
		           		 	        rStatus: '1',
			           		 	    customerId:customerId
		           		 	    });
		           		 	    selectWindow.show();
		           		    }
		                }]
		            }, {
		                xtype:'textfield',
		                fieldLabel: '建筑面积(㎡)',
		                anchor: '80%',
		                name: 'buildingArea',
		                readOnly:true
		            }, {
		                xtype:'textfield',
		                fieldLabel: '分摊面积(㎡)',
		                anchor: '80%',
		                name: 'sharingArea',
		                readOnly:true
		            }, {
		                xtype:'textfield',
		                fieldLabel: '折前单价(元)',
		                anchor: '80%',
		                name: 'calculateUnitPrice',
		                readOnly:true
		            },{
		                xtype:'textfield',
		                fieldLabel: '房源ID',
		                name: 'id',
		                readOnly:true,
		                hidden:true
		            }]
		        }, {
		            items: [{
		                xtype:'textfield',
		                fieldLabel: '房源状态',
		                anchor: '80%',
		                name: 'roomStatusName',
		                readOnly:true
		            },{
		                xtype:'textfield',
		                fieldLabel: '套内面积(㎡)',
		                anchor: '80%',
		                name: 'innerArea',
		                readOnly:true
		            },{
		                xtype:'textfield',
		                fieldLabel: '计价面积(㎡)',
		                anchor: '80%',
		                name: 'billingArea',
		                id:'billingArea',
		                readOnly:true
		            },{
		                xtype:'textfield',
		                fieldLabel: '折前总价(元)',
		                anchor: '80%',
		                name: 'totalPrice',
		                readOnly:true
		            }]
		        }]
	    };
		var items=[row_1];
		var initConfigg = {
				id:'estatePanel',
				title:"房产信息",
				bodyStyle: 'padding:5px 5px 0',
		        minHeight: 200,
		        fieldDefaults: {
		            labelAlign: 'left',
		            msgTarget: 'side',
		            margin: 5
		        },
		        items:items
		};
		Ext.apply(this,initConfigg);
		this.callParent(arguments);
	}
});


var oldSubscribeForm = Ext.create("Ext.form.FormPanel", {
	autoWidth: true,
	autoHeight: true,
	title:"原认购信息",
	fieldDefaults: {
        labelWidth: 120,
        labelAlign: "right",
        margin: "0 0 10 0"
    },
	items: [
		{
			xtype: "fieldcontainer", layout: "hbox",
			items: [
				{xtype: "displayfield", name: "customerName", fieldLabel: "客户姓名", width: 400},
				{xtype: "displayfield", name: "receivedPayAmount", fieldLabel: "已收金额", width: 400, renderer: Ext.util.Format.numberRenderer('0,000.00')}
			]
		},
		{xtype: "displayfield", name: "checkDateStr", fieldLabel: "业务日期", width: 400,
	    	renderer : function(val) {
				
				return val;
			}
		},
		{
			xtype: "fieldcontainer", layout: "hbox",
			items: [
				{xtype: "displayfield", name: "comboxRoomName", fieldLabel: "原楼盘名称及房号", width: 400},
				{xtype: "displayfield", name: "calculateArea", fieldLabel: "原计价面积", width: 400, renderer: Ext.util.Format.numberRenderer('0,000.00')}
			]
		},
		{
			xtype: "fieldcontainer", layout: "hbox",
			items: [
				{xtype: "displayfield", name: "conversionPrice", fieldLabel: "原房屋单价", width: 400, renderer: Ext.util.Format.numberRenderer('0,000.00')},
				{xtype: "displayfield", name: "lumpsumPrice", fieldLabel: "原折前总价", width: 400, renderer: Ext.util.Format.numberRenderer('0,000.00')}
			]
		}
	]
});

oldSubscribeForm.getForm().load({
    url: contextPath + '/marketing/businessAbnorma/subscribeChangeRoomById',
    params: {"id": old_subscribeId},
    success: function(form, action){
    	console.log(form);
	},
    failure: function(form, action) {
    	 Ext.Msg.alert('提示', '加载数据失败!');
	}
});

Ext.define('customer.subscribe.add.customerPanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
		var me=this;
		var documentTypeStore = Ext.create('Ext.data.Store', {
		    fields: ['value', 'name'],
		    data :documentType
		});
		var row_1={
				fieldDefaults: {
			            labelAlign: 'top',
			            msgTarget: 'side'
			    },
			    border: false,
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
				layout: 'hbox',
				items: [{
		            items: [{
		            	xtype:'container',
		            	layout:'hbox',
		            	anchor: '80%',
		            	items:[{
		            		xtype:'textfield',
			                fieldLabel: '客户姓名',
			                anchor: '80%',
			                name: 'customerName',
			                readOnly:true,
			                allowBlank:false
			                }
		            	]
		                
		            }, {
		                xtype:'combobox',
		                fieldLabel: '<font style="color: #e90000;">*</font>证件类型',
		                anchor: '80%',
		                name: 'peDocumentTypeName',
		                store: documentTypeStore,
					    queryMode: 'local',
					    typeAhead: true,
					    displayField: 'name',
					    valueField: 'value',
					    allowBlank: false,
					    blankText: "客户信息证件类型不能为空"
		            }, {
		                xtype:'textfield',
		                fieldLabel: '<font style="color: #e90000;">*</font>证件号码',
		                anchor: '80%',
		                name: 'peDocumentNumber',
		                allowBlank: false,
		                blankText: "客户信息证件号码不能为空",
		                maxLength:18
		            }, {
		                xtype:'textfield',
		                fieldLabel: '<font style=\"color: #e90000;\">*</font>联系电话',
		                anchor: '80%',
		                name: 'customerPhone',
		                readOnly:true
		            }]
		        }, {
		            items: [{
		                xtype:'textfield',
		                fieldLabel: '<font style="color: #e90000;">*</font>邮寄地址',
		                anchor: '80%',
		                name: 'peContactAddress',
		                allowBlank: false,
		                blankText: "邮寄地址不能为空"
		            },{
		                xtype:'textfield',
		                fieldLabel: '<font style="color: #e90000;">*</font>邮编',
		                anchor: '80%',
		                name: 'pePostcode',
		                allowBlank: false,
		                blankText: "邮编不能为空"
		            },{
		                xtype:'textfield',
		                fieldLabel: '客户来源',
		                anchor: '80%',
		                name: 'customerOriginName',
		                readOnly:true
		            },{
		                xtype:'textfield',
		                fieldLabel: 'ID',
		                anchor: '80%',
		                name: 'id',
		                id:'customerId',
		                readOnly:true,
		                hidden:true
		            }]
		        }]
	    };
		var gridStore = Ext.create('Ext.data.Store', {
			id:'familyMemberGridStore',
		    fields: ["memberName","documentType","documentNumber","mobile"],
		    //是否在服务端排序 （true的话，在客户端就不能排序）
		    remoteSort: false,
		    proxy: {
		        type: 'ajax',

		        url: contextPath+'/customer/familyMember/findList?buyId='+old_subscribeId,

		        reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
		            type: 'json', //返回数据类型为json格式
		            root: 'obj'
		        },
		        actionMethods: {read: 'POST'}
		    }
		});
		var columns = [{
			text : "姓名",
			dataIndex : 'memberName',
			width:'20%',
			editor: {
                xtype: 'textfield'
            }
		}, {
			text : "<font style=\"color: #e90000;\">*</font>证件类型",
			dataIndex : 'documentType',
			width:'20%',
			editor: new Ext.form.field.ComboBox({
			    store: documentTypeStore,
			    queryMode: 'local',
			    displayField: 'name',
			    valueField: 'value'
            }),
            renderer: function(value,metadata,record){  
                var index = documentTypeStore.find('value',value);  
                if(index!=-1){  
                    return documentTypeStore.getAt(index).data.name;  
                }  
                return value;  
            }
		}, {
			text : "<font style=\"color: #e90000;\">*</font>证件号码",
			dataIndex : 'documentNumber',
			width:'20%',
			editor: {
                xtype: 'textfield',
                maxLength:18
            }
		},{
				text : "手机号码",
				dataIndex : 'mobile',
				width:'20%',
				editor: {
	                xtype: 'textfield'
	            }
		},{
        	text:'操作',
        	xtype : 'actioncolumn',
        	items:[{
        		 iconCls:'icon-delete',
        		 tooltip: '删除', 
        		 handler: function(grid, rowIndex, colIndex) {
        			 gridStore.removeAt(rowIndex);
        			if(gridStore.getCount()<4){
   				    	Ext.getCmp("insertBtn").setVisible(true);
   				    	Ext.getCmp("customerSelectBtn").setVisible(true);
   				    }
        		 }
        	}]
        }];
		var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
	        clicksToEdit: 1
	    });
		var row_2=Ext.create('Ext.grid.Panel', {
			id:'familyMemberGridPanel',
			region : 'south',
			title:"共同购房者",
			minHeight:200,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
			store : gridStore,
			columns : columns,
			plugins: [cellEditing],
			tbar:[{text:'新增',iconCls:'icon-add',id:'insertBtn',
				handler:function(){
				    Ext.define('Record', { 
			            extend: 'Ext.data.Model'
				    }); 
				    var record  = new Record(); 
				    gridStore.insert(0, record);
				    cellEditing.startEditByPosition({
				        row: 0, 
				    	column: 0
				    });
				    if(gridStore.getCount()>=4){
				    	Ext.getCmp("insertBtn").setVisible(false);
				    	Ext.getCmp("customerSelectBtn").setVisible(false);
				    }
			}
			},{
            	xtype:'button',
            	text:'选择客户',
            	margin: 5,
            	iconCls:'icon-search',
            	id:'customerSelectBtn',
       		    handler: function() {
       		    	var projectId = Ext.getCmp("projectId").getValue();
       		 	    var selectWindow=Ext.create('component.customer.selectWindow',{
       		 			callbackFun: function (record) {
   		 	          		var result=Ext.JSON.decode(record);
		           		 	Ext.define('Record', { 
					            extend: 'Ext.data.Model',
					            fields: ["memberName","documentType","mobile","documentNumber"]
						    }); 
						    var record  = new Record({
						    	 memberName:result.customerName,
						    	 documentType:result.peDocumentType,
						    	 mobile:result.customerPhone,
						    	 documentNumber:result.peDocumentNumber
						    }); 
						    gridStore.insert(0, record);
						    
						    if(gridStore.getCount()>=4){
						    	Ext.getCmp("insertBtn").setVisible(false);
						    	Ext.getCmp("customerSelectBtn").setVisible(false);
						    	return;
						    }
						    
       		 	        },
       		 	        projectId: projectId,
       		 	        resourcesCode:'menu_0006_0001'
       		 	    });
       		 	    selectWindow.show();
    		    }
			}
			]
		});
		var items=[row_1,row_2];
		var initConfigg = {
				id:'customerPanel',
		        title:"客户信息",
		        minHeight:320,
		        fieldDefaults: {
		            labelAlign: 'left',
		            msgTarget: 'side',
		            margin: 5
		        },
		        items:items
		};
		Ext.apply(this,initConfigg);
		this.callParent(arguments);
	}
});
Ext.define('customer.subscribe.add.subscribePanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
		var me=this;
		var row_1={
				fieldDefaults: {
			            labelAlign: 'left',
			            msgTarget: 'side'
			    },
			    border: false,
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
				layout: 'hbox',
				items: [{
		            items: [
		            {
		                xtype:'textfield',
		                fieldLabel: '认购编号',
		                //anchor: '80%',
		                name:'subscribeCode'
		            },{
		                xtype:'textfield',
		                fieldLabel: '折前总价(元)',
		                //anchor: '80%',
		                readOnly:true,
		                name: 'totalPrice'
		            }, {
		            	xtype: 'numberfield',
		                fieldLabel: '合同金额(元)',
		                //anchor: '80%',
		                name:'discountTotalAmount',
		                hideTrigger:true,
		                readOnly:true
		            }]
		        }, {
		            items: [{
		                xtype:'textfield',
		                fieldLabel: '折前单价(元)',
		                name:'calculateUnitPrice',
		                readOnly:true
		            }, {
		                xtype:'numberfield',
		                fieldLabel: '签约单价(元)',
		                //anchor: '80%',
		                name: 'discountAmount',
		                hideTrigger:true,
		                readOnly:true
		            }]
		        }]
	    };
		
		var calculationFloor=function(){
			//底价算法
			var subscribeForm =  me.getForm();
			var subscribe=me.getForm().getValues();
			//折扣金额=折前总价-折后总价
			
			var calculationAmount = subscribe['discountAfterPrice'];
			
			var totalPrice=subscribe['totalPrice'];
			if(calculationAmount==""||calculationAmount==null){
				calculationAmount=totalPrice;
			}
			//移除折扣金额的change事件
			var newdiscountAfterAmount = totalPrice-calculationAmount;
			//subscribeForm.findField('discountAfterAmount').clearListeners();
			subscribeForm.findField('discountAfterAmount').setValue(newdiscountAfterAmount);
			//折后比例=折后总价/折前总价
			//var newdiscountRate = ((calculationAmount/totalPrice)*100).toFixed(0);
			//合同金额
			//subscribeForm.findField('discountTotalAmount').setValue(calculationAmount);
			//subscribeForm.findField('discountRate').setValue(newdiscountRate);
		}
		var calculationDiscount=function(){
			var subscribe=me.getForm().getValues();
			var isCalculate=subscribe['isCalculate'];
			var billingArea = Ext.getCmp("billingArea").getValue();
			if(isCalculate=="0")return;
			//折前单价
			var calculateUnitPrice=subscribe['calculateUnitPrice'];
			if(!calculateUnitPrice)return;
			//折前总价
			var totalPrice=subscribe['totalPrice'];
			if(!totalPrice)return;
			
			//折后总价
			var discountAfterPrice = me.getForm().findField("discountAfterPrice").getValue();
			//折扣金额
			var discountAfterAmount = me.getForm().findField("discountAfterAmount").getValue();
			discountAfterPrice = totalPrice - discountAfterAmount;
			//当前折扣
			var nowDiscountRate=(100-((discountAfterAmount/totalPrice)*100)).toFixed(2);
			var nowTotalPrice=totalPrice-discountAfterAmount;
			var nowUnitPrice ='0';
			if(billingArea>0){
				nowUnitPrice=(nowTotalPrice/billingArea).toFixed(2);
			}
			
			//折后单价
			me.getForm().findField("discountRate").setValue(parseInt(nowDiscountRate, 0));
			me.getForm().findField("discountAmount").setValue(nowUnitPrice);
			me.getForm().findField("discountTotalAmount").setValue(nowTotalPrice);
			me.getForm().findField("discountAfterPrice").setValue(discountAfterPrice);
		};
		var row_2={
				fieldDefaults: {
		            labelAlign: 'left',
		            msgTarget: 'side'
		        },
		        collapsible: true,
		        //collapsed: true,
				xtype: 'fieldset',
                title:'折扣信息',
                //layout: 'anchor',
                defaultType: 'textfield',
                items:[{
		            	 xtype:'textfield',
			             fieldLabel: '折后总价(元)',
			             id:'discountAfterPrice',
			             name:'discountAfterPrice',
			             listeners: {
			                    change: function(field, value) {
			                        calculationFloor();
			                    }
			                }
			             
		            },{
                	xtype: 'numberfield',
                	fieldLabel: '折扣金额(元)',
                    name: 'discountAfterAmount',
                    hideTrigger:true,
                    minValue: 0,
                    listeners: {
	                    change: function(field, value) {
	                        calculationDiscount();
	                    }
	                }
                },{
	            	xtype:'container',
	            	layout:'hbox',
	            	anchor: '80%',
	            	items:[{
	            		xtype: 'numberfield',
		                fieldLabel:'折扣比例(%)',
		                id:'discountRate',
		                name:'discountRate',
		                hideTrigger:true,
		                readOnly:true
		                
	            	},{
	            		xtype:'displayfield',
	            		hideLabel:true,
	            		name:'discountRateDisplay'
	            	},{
	            		xtype: 'hiddenfield',
		                name:'discountRateHidden'
	            	},{
	            		xtype: 'hiddenfield',
		                name:'isCalculate',
		                value:'0'
	            	},{
	            		xtype: 'hiddenfield',
		                name:'floorType'
	            	}]
	                
	            },{
                	xtype: 'textareafield',
                	fieldLabel: '折扣说明',
                	anchor: '50%',
                    name: 'discountNote'
                }]
	    };
		var dealCategoryStore = Ext.create('Ext.data.Store', {
		    fields: ['value', 'text'],
		    data : [
                {"value":"1", "text":"推荐成交"},
		        {"value":"2", "text":"单独成交"},
		        {"value":"3", "text":"共同成交"}
		    ]
		});
		
		gridStoreJingJ = Ext.create('Ext.data.Store', {
			id:'agentGridStore',
		    fields: ["relationAgentid","proportionCommission"],
		    //是否在服务端排序 （true的话，在客户端就不能排序）
		    remoteSort: false,
		    proxy: {
		        type: 'ajax',
		        url: '',
		        reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
		            type: 'json', //返回数据类型为json格式
		            root: 'obj'
		        }
		    }
		});
		var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
	        clicksToEdit: 1
	    });
		
		var columns_3 = [{
			text: '经纪人',
            sortable : false,
            width:'20%',
            dataIndex: 'relationAgentid',
            name:'relationAgentid',
            editor:new Ext.form.field.ComboBox({
            	  queryMode:'local',
                  store:userIdStore,
                  valueField:'id',
                  displayField:'userName',
                  allowBlank:false,
                  blankText:'不能为空'  
            }),  
            renderer: function(value,metadata,record){  
                var index = userIdStore.find('id',value);  
                if(index!=-1){  
                    return userIdStore.getAt(index).data.userName;  
                }else{
                	return value;
                }  
            }
        },{
			text : "分佣比例(%)",
			dataIndex: 'proportionCommission',
			id:'proportionCommission',
			name:'proportionCommission',
			width:'20%',
			editor: {
                xtype: 'numberfield',
                hideTrigger:true
			}
        },{
        	text:'操作',
        	xtype : 'actioncolumn',
        	items:[{
        		 iconCls:'icon-delete',
        		 tooltip: '删除', 
        		 handler: function(grid, rowIndex, colIndex) {
        			 gridStoreJingJ.removeAt(rowIndex);
        			 if(gridStoreJingJ.getCount()<3){
   				    	Ext.getCmp("insertAgentBtn").setVisible(true);
   				     }
        		 }
        	 }]
        }];
		var row_3=Ext.create('Ext.grid.Panel', {
			id:'agentPanel',
			title:"经纪人",
			minHeight:150,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
	        store : gridStoreJingJ,
			columns : columns_3,
			plugins: [cellEditing],
			tbar:[{text:'新增',iconCls:'icon-add',id:'insertAgentBtn',
				handler:function(){
					Ext.define('Record', { 
			            extend: 'Ext.data.Model' 
				    }); 
					var record  = new Record(); 
					gridStoreJingJ.insert(0, record);
					cellEditing.startEditByPosition({
				        row: 0, 
				    	column: 0
				    });
					if(Ext.getCmp("dealCategory").getValue() == '3'){
						if(gridStoreJingJ.getCount()>=3){
	  				    	Ext.getCmp("insertAgentBtn").setVisible(false);
	  				    }
					}else{
						if(gridStoreJingJ.getCount()>=1){
	  				    	Ext.getCmp("insertAgentBtn").setVisible(false);
	  				    }
					}
				}
			}]
		});
		
		var items=[row_1,row_2,{
        	xtype: 'numberfield',
            fieldLabel: '已收认筹金(元)',
            name:'haveReceivedPayDepositAmount',
            hideTrigger:true,
            readOnly:true
        },{
        	xtype: 'numberfield',
            fieldLabel: '<font style=\"color: #e90000;\">*</font>应收认购金(元)',
            name:'depositReceivable',
            minValue: 0,
            allowBlank:false,
            hideTrigger:true,
            blankText:'应收认购金不能为空'
        },{
        	xtype: 'datefield',
            fieldLabel: '<font style=\"color: #e90000;\">*</font>认购日期',
            name:'subscribeDate',
            format: 'Y-m-d',
            value: new Date(),
            allowBlank:false,
            blankText:'认购日期不能为空',
            listeners:{
               select:function (field,value) {
            	    var nowData=addDate(value,7);
            	    Ext.getCmp("conversionSignDate").setMaxValue(nowData);
               }
            }
        },{
            xtype:'datefield',
            fieldLabel: '<font style=\"color: #e90000;\">*</font>认购转签约日期',
            //anchor: '80%',
            name:'conversionSignDate',
            id:'conversionSignDate',
            format: 'Y-m-d',
            allowBlank:false,
            blankText:'不能为空',
            maxValue: addDate(new Date(),7)
        },{
        	xtype: 'textareafield',
            fieldLabel: '换房原因',
            anchor: '50%',
            name:'remark'
        },{
        	xtype: 'combobox',
            fieldLabel: '成交类别',
            name:'dealCategory',
            id:'dealCategory',
            store: dealCategoryStore,
            queryMode: 'local',
            displayField: 'text',
            valueField: 'value',
            value:'2',
            listeners: {
                change: function(field,value) {
                	if(value=="3"){
                		if(gridStoreJingJ.getCount()<3){
                			Ext.getCmp("insertAgentBtn").setVisible(true);
                		}
                		Ext.getCmp("proportionCommission").setVisible(true);
            			Ext.getCmp("referenceName").hide();
            			Ext.getCmp("referenceButton").hide();
            			Ext.getCmp("referenceProportion").hide();
                	}else{
                		if(value=="1"){
                			Ext.getCmp("referenceName").show();
                			Ext.getCmp("referenceButton").show();
                			Ext.getCmp("referenceProportion").hide();
                    		Ext.getCmp("proportionCommission").setVisible(false);
                		}else{
                			Ext.getCmp("referenceName").hide();
                			Ext.getCmp("referenceButton").hide();
                			Ext.getCmp("referenceProportion").hide();
                    		Ext.getCmp("proportionCommission").setVisible(true);
                		}
                		for(var i = 1; i < gridStoreJingJ.getCount(); i++){
                			gridStoreJingJ.removeAt(i);
                		}
//                		if(value=="2"){
//                			Ext.getCmp("proportionCommission").setVisible(false);
//                		}
                	}
                }
            }
        },{
        	layout: 'column',
        	items: [
            		{xtype:"textfield", name:"referenceId",id:'referenceId', hidden:true},
            		{xtype:"textfield", id:'referenceName', fieldLabel:'推荐人姓名', hidden:true, name:"referenceName"},
            		{
	                	xtype:'button',
	                	text:'选择客户',
	                	id:'referenceButton',
	                	margin: 5,
	                	iconCls:'icon-search', 
	           		    handler: function() {
	           		    	var projectId = Ext.getCmp("projectId").getValue();
/*	           		 	    var selectWindow=Ext.create('component.user.selectWindow',{
	           		 			callbackFun: function (record) {
		           		 	  		var result=Ext.JSON.decode(record);
		           		 	  		Ext.getCmp("referenceName").setValue(result.userName);
		           		 	  		Ext.getCmp("referenceName").setDisabled(true);
		           		 	  		Ext.getCmp("referenceId").setValue(result.id);
	           		 	        }
	           		 	    	,projectId: projectId
	           		 	    });*/
		           		 	var selectWindow=Ext.create('component.customer.selectWindow',{
		       		 			callbackFun: function (record) {
		   		 	          		var result=Ext.JSON.decode(record);
		   		 	          		var customerName=result.customerName;
		   		 	          		var customerId=result.id;
		   		 	          	    Ext.getCmp("referenceName").setValue(customerName);
	           		 	  		    Ext.getCmp("referenceName").setDisabled(true);
	           		 	  		    Ext.getCmp("referenceId").setValue(customerId);  
		       		 	        },
		       		 	        projectId: projectId,
		       		 	        resourcesCode:'menu_0006_0001'
		       		 	    });
	           		 	    selectWindow.show();
	        		    }, hidden:true
	                },
            		{xtype:"numberfield",hideTrigger:true, id:'referenceProportion', fieldLabel:'推荐人比例', hidden:true, name:"referenceProportion",maxLength:3,regex:/^[1-9]\d*$/}
            ]
//
//        	xtype:'combobox',  
//            id:'userName',  
//            store: userIdStore,
//            displayField: "userName",           
//            valueField: "id",  
//            fieldLabel:'经纪人',  
//            width:200,
//			name:'agentId',
//			queryMode : 'local',
//			allowBlank:false,
//            blankText:'不能为空',  
//            listeners:{
//            	'change':function(value){
//            		if(value.lastValue){
//            			var index = userIdStore.find('id',value.lastValue);  
//            			if(index!=-1){  
////            				console.log(userIdStore.getAt(index));
////            				console.log(userIdStore.getAt(index).data);
////         		 	        return userIdStore.getAt(index).data.userName;
//         		 	        Ext.getCmp('userName').setValue(userIdStore.getAt(index).data.id);
//            			}
//            		}
//            	}
//            }
        },row_3];
		
		var initConfigg = {
				id:"subscribeInfoForm",
		        title:"认购信息",
		        minHeight:200,
		        fieldDefaults: {
		            labelAlign: 'left',
		            msgTarget: 'side',
		            margin: 5
		        },
		        items:items
		};
		Ext.apply(this,initConfigg);
		this.callParent(arguments);
	}
});


Ext.define('customer.subscribe.addPanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
		var estatePanel= Ext.create("customer.subscribe.add.estatePanel");
		var customerPanel= Ext.create("customer.subscribe.add.customerPanel");
		var subscribePanel= Ext.create("customer.subscribe.add.subscribePanel");
		var fileAttachment = Ext.create('component.file.attachment',{
		    objectId: '',
		    imageType: "2",
		    contextPath:contextPath
		});
		var submitFun=function(startProcess){
		
			//房源信息
       	var estateForm=estatePanel.getForm();
       	var subscribeId = estateForm.findField("subscribeId").getValue();
       	 var roomId=estateForm.findField("id").getValue();
       	 var billingArea=estateForm.findField("billingArea").getValue();
       	 var calculateUnitPrice=estateForm.findField("calculateUnitPrice").getValue();
       	 var totalPrice=estateForm.findField("totalPrice").getValue();
       	 if(roomId=="" || null==roomId){
       		 Ext.Msg.alert('提示', '请选择房源');
           	 return;
       	 }
       	 if(totalPrice=="" || null==totalPrice){
       		 Ext.Msg.alert('提示', '房源折前总价未设置');
           	 return;
       	 }
       	 //客户信息
       	 var customerForm=customerPanel.getForm();
       	 var customerId=customerForm.findField("id").getValue();
		if(!customerForm.isValid()){
			return false;
		}
       	 if(customerId=="" || null==customerId){
       		 Ext.Msg.alert('提示', '请选择客源');	
           	 return;
       	 }
       	 
       	 //应收认购金+已收认筹金 不能大于合同金额
	      var vaildHaveReceivedPayDepositAmount=parseFloat(subscribePanel.getForm().findField("haveReceivedPayDepositAmount").getValue());
	      var vaildDepositReceivable=parseFloat(subscribePanel.getForm().findField("depositReceivable").getValue());
	      var vaildDiscountTotalAmount=parseFloat(subscribePanel.getForm().findField("discountTotalAmount").getValue());
       	 //认购信息
	      if(vaildHaveReceivedPayDepositAmount+vaildDepositReceivable>vaildDiscountTotalAmount){
	    	  Ext.Msg.alert('提示', '认筹认购金相加不能大于合同金额！');
	    	  return;
	      }
	     
      	var form = subscribePanel.getForm();
      	if(form.isValid()){
      		var familyMemberGridStore=customerPanel.getComponent("familyMemberGridPanel").getStore();
          	 var jsonArray=[];
       		 var recordsCount=familyMemberGridStore.getCount();
       		 if(recordsCount>0){
       			 for(var i=0;i<recordsCount;i++){
       				 var documentNumber = familyMemberGridStore.getAt(i).data.documentNumber;
       				 if(documentNumber==null||documentNumber==""){
    					 Ext.Msg.alert('提示', '请填写共同购房者证件号码!');
    		           	 return;
    				 }else{
    					 
    					 //验证手机号码的正确性
    					 var userPhone = familyMemberGridStore.getAt(i).data.mobile;
    					 if(userPhone != null && userPhone != ""){
//    						 var regTel = /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
//    						 if(!regTel.test(userPhone)){
//    							 Ext.Msg.alert('提示', '请输入正确的手机号码!');
//    							 return;
//    						 }
	    					 Ext.Ajax.request({
	             				url: contextPath+'/common/mobile/verifyingMobile',
	             				params: {
	             					mobile: userPhone,
	             				},
	             				method: 'POST',
	             				async: false,
	             				success: function(response){
	             					var text = Ext.decode(response.responseText);
	             					if(text.result=="1"){
	             						if(text.flag != "1"){
	             							Ext.MessageBox.alert('提示', '请输入正确的手机号码');
	             							return;
	             						}
	             					}
	             				}
	             			 });
    					 }
    					 
    					 jsonArray.push(Ext.JSON.encode(familyMemberGridStore.getAt(i).data));
    				 }
       	    	 }
       		 }

          	 //认购信息
          	 var subscribe=subscribePanel.getForm().getValues();
	       	 var signedForm=subscribePanel.getForm();
       		 var agentGridStore=subscribePanel.getComponent("agentPanel").getStore();
         	 var jsonArrayAgent=[];
         	var number = 0;
      		 var recordsCount=agentGridStore.getCount();
      		 if(recordsCount>0){
      		 	if(subscribe['dealCategory'] != 1){
                    var reg = /^\d+(?:\.\d{1,2})?$/;
                    for(var i=0;i<recordsCount;i++){
                        //验证数据
                        var proportionCommission = agentGridStore.getAt(i).data.proportionCommission;
                        if(reg.test(proportionCommission)==false){
                            Ext.Msg.alert('提示', '分佣比例请输入数字!');
                            return;
                        }else{
                            number=number+parseFloat(proportionCommission);
                            jsonArrayAgent.push(Ext.JSON.encode(agentGridStore.getAt(i).data));
                        }
                    }
				}else{
                    for(var i=0;i<recordsCount;i++){
						jsonArrayAgent.push(Ext.JSON.encode(agentGridStore.getAt(i).data));
                    }
				}

      		 }else{
      			Ext.Msg.alert('提示', '请选择经纪人');
          		return;
      		 }
      		 if(number>100&&subscribe['dealCategory'] == 3){
      			 Ext.Msg.alert('提示', '分佣比例累加不能超过100%!');
      			 return;
      		 }
      		 if(number<100&&subscribe['dealCategory'] == 3){
      			Ext.Msg.alert('提示', '分佣比例累加要等于100%!');
     			 return;
      		 }

      		 var referenceName=signedForm.findField("referenceName").getValue();
      		 var referenceProportion=signedForm.findField("referenceProportion").getValue();
      		 var referenceId=signedForm.findField("referenceId").getValue();
   			if(subscribe['dealCategory'] == 1){
	           	 if(referenceName=="" || null==referenceName){
	           		 Ext.Msg.alert('提示', '请填写推荐人姓名');
	               	 return;
	           	 }
	           	 if(referenceProportion=="" || null==referenceProportion){
	           		 /*Ext.Msg.alert('提示', '请填写推荐人比例');
	               	 return;*/
	           		referenceProportion="0"
	           	 }
//          		var ionum = number+parseInt(subscribe['referenceProportion']);
//          		if(ionum>100){
//              		Ext.Msg.alert('提示', '推荐人比例和分佣比例总和不能超过100%');
//              		return;
//          		}
//          		if(ionum<100){
//              		Ext.Msg.alert('提示', '推荐人比例和分佣比例总和不能小于100%');
//              		return;
//          		}
   			}
          	 
          	 for(var i = 0; i < recordsCount; i++){
          		var jsonAgent = eval("(" + jsonArrayAgent[i] + ")");
      			if(jsonAgent.relationAgentid == ""){
              		Ext.Msg.alert('提示', '请选择经纪人');
              		return;
              	}
//      			if(subscribe['dealCategory'] == 1){
//      				if(jsonAgent.proportionCommission == undefined 
//          					|| jsonAgent.proportionCommission == ""){
//                  		Ext.Msg.alert('提示', '请填写分佣比例');
//                  		return;
//                  	}
//      			}
      			if(subscribe['dealCategory'] == 3){
      				if(jsonAgent.proportionCommission == undefined 
          					|| jsonAgent.proportionCommission == ""){
                  		Ext.Msg.alert('提示', '请填写分佣比例');
                  		return;
                  	}
      			}
      		 }
          	 //判断证件类型是否做了修改
             var peDocumentType = customerForm.findField("peDocumentTypeName").getValue();
             if(isNaN(peDocumentType)){
            	 peDocumentType = "";
             }

          	 var params={};
          	 //房源信息
          	 params.id=subscribeId;
          	 params.roomId=roomId;
          	 params.calculateArea=billingArea;
          	 params.conversionPrice=calculateUnitPrice;
          	 params.lumpsumPrice=totalPrice;
          	 //客户信息
          	 params.customerId=customerId;
          	 params.peDocumentTypeName = peDocumentType;
          	 params.peDocumentNumber = customerForm.findField("peDocumentNumber").getValue();
          	 //验证证件号是否正确
      		 var ver = verifyIDNumber(customerForm.findField("peDocumentTypeName").getRawValue(), params.peDocumentNumber);
         	 if(ver == false){
         		 return false;
         	 }
          	 params.peContactAddress = customerForm.findField("peContactAddress").getValue();
          	 params.pePostcode = customerForm.findField("pePostcode").getValue();
          	 params.customerName = customerForm.findField("customerName").getValue();

          	 //认购信息
          	 params.discountAfterPrice=subscribe['discountAfterPrice'];
          	 params.floorType=subscribe['floorType'];
          	 params.discountAmount=subscribe['discountAfterAmount'];
          	 params.subscribeCode=subscribe['subscribeCode'];
          	 params.conversionSignDate=subscribe['conversionSignDate'];
          	 params.discountRate=subscribe['discountRate'];
          	 params.subscribePrice=subscribe['discountAmount'];
          	 params.subscribeAmount=subscribe['discountTotalAmount'];
          	 params.depositReceivable=subscribe['depositReceivable'];
          	 params.subscribeDate=subscribe['subscribeDate'];
          	 params.dealCategory=subscribe['dealCategory'];
          	 params.remark=subscribe['remark'];
          	 params.discountNote=subscribe['discountNote'];
          	 params.didTime=subscribe['subscribeDate'];
          	 var discountRateHidden=subscribe['discountRateHidden'];
          	 var discountRate=subscribe['discountRate']
           	 //params.agentId=subscribe['agentId'];
          	 //当前折扣<最小折扣 则需要发起折扣审批
          	 
          	 //当是折扣的时候
          	 if(subscribe['floorType']=="1"){
          		if(parseFloat(discountRate)<parseFloat(discountRateHidden)){
              		params.discountApproval='1';
              	 }else{
              		params.discountApproval='0'; 
              	 }
          		console.log("折后折扣率/低价和价格方案设置对比："+parseFloat(discountRate)+":"+parseFloat(discountRateHidden));
          	 }else if(subscribe['floorType']=="0"){
          		 //如果折后金额低于底价时 要发起折扣审批
          		if(parseFloat(subscribe['discountAfterPrice'])<parseFloat(discountRateHidden)){
              		params.discountApproval='1';
              	}else{
              		params.discountApproval='0'; 
              	}
          		console.log("折后折扣率/低价和价格方案设置对比："+parseFloat(subscribe['discountAfterPrice'])+":"+parseFloat(discountRateHidden));
          	 }else{
          		Ext.Msg.alert('提示', '价格方案低价方式设置错误');
          		return; 
          	 }
          	 if(null==params.discountApproval || params.discountApproval==""){
          		Ext.Msg.alert('提示', '是否折扣审批参数错误');
          		return;
          	 }
          	 console.log("是否发起折扣审批(0否：1是)："+params.discountApproval);
          	 var fileArr =fileAttachment.getFileArrs();
          	 params.familyMember=jsonArray;
          	 params.agents = jsonArrayAgent;
             params.referenceName = referenceName;
             params.referenceProportion = referenceProportion;
             params.referenceId = referenceId;
             //流程图片
             params.imageType = "2";
             params.fileArr = fileArr;
          	 var resultJson=Ext.JSON.encode(params);
          	 if(startProcess){
          		 Ext.getCmp("save_button").setVisible(false);
          	 }
          	 Ext.Msg.wait("正在处理，请稍等...","");
          	 Ext.Ajax.request({
           	    url: contextPath+'/marketing/businessAbnorma/subscribeChangeRoomAdd',
           	    params: {
           	    	params: resultJson,
           	    	startProcess:startProcess,
           	    	roomId:roomId,
           	    	subscribeId:old_subscribeId
           	    },
           	    method: 'POST',
           	    success: function(response){
           	    	Ext.Msg.hide();
           	        var text = Ext.decode(response.responseText);
           	        if(text.res=="1"){
           	        	Ext.getCmp("subscribeId").setValue(text.obj);
           	        	fileAttachment.deleteBtnHidden();
           	        	Ext.Msg.alert('提示', );
	           	        Ext.MessageBox.alert("系统提示",text.resMsg, function(but) {
	           	        	
	           	        	
		                }); 
           	        }else if(text.res=="100"){
           	            Ext.getCmp("save_button").setVisible(true);
           	            token = text.obj;
           	            Ext.Msg.alert('提示', '权限不足！');
           	        }else{
           	        	Ext.getCmp("save_button").setVisible(true);
           	        	token = text.obj;
           	        	Ext.Msg.alert('提示', '认购换房失败！原因：'+text.resMsg);
           	        }
           	    }
           	});
      	}

		};
		var defaultConfigg = {
				buttonAlign:'center',
				defaults: {  
		            split: true,    //有分割线  
		            collapsible: true  //可以折叠
		        },
		        renderTo:Ext.getBody(),
				items:[oldSubscribeForm,estatePanel,customerPanel,subscribePanel, fileAttachment],
				buttons:[
				         {xtype: "button",id:'save_button',text: "提交审核",handler: function(){
				        	 submitFun(true);
				         }},
				         {xtype: "button",text: "返回",handler: function(){
				        	 var tabKey = "abs_"+old_subscribeId;
			        		 parent.TabControlRemove(tabKey);
				        	
				         }}
				]
		};
		Ext.apply(this,defaultConfigg);
		this.callParent(arguments);
	}
});

//计算days天后的日期(时间，天数)
function addDate(date,days){ 
	var d=new Date(date); 
	d.setDate(d.getDate()+days); 
	//var month=d.getMonth()+1; 
	//var day = d.getDate(); 
	//var val = d.getFullYear()+""+month+""+day; 
	return d; 
}

//校验证件号码
function verifyIDNumber(type, code){
	var url = "";
	if(type == '身份证'){
		url = "verifyIDCard";
	} else if(type == '营业执照'){
		url = "verifyBusinessLicense";
	} else {
		return true;
	}
	var flag = true;
	Ext.Ajax.request({
		url: contextPath+'/common/idNumber/'+url,
		params: {
			"code": code,
		},
		method: 'POST',
		async: false,
		success: function(response){
			var text = Ext.decode(response.responseText);
			if(text == false){
				Ext.MessageBox.alert('提示', '请输入正确的'+type);
				flag = false;
			}
		}
	});
	return flag;
}